<?php


namespace app\api\service;


use think\Request;

class QrCode{

    protected  $url;

    public function __construct(){
        $accessToken = new Accesstoken();
        $token = $accessToken->getToken();
        $this->url = sprintf(config('wxinfo.qrUrl'),$token['access_token']);
    }


    public function getBaseCode($scene = '.',$page='pages/index/index'){

        $codeData = [
            'page' => $page,
            'scene' =>$scene
        ];

        $tmp = https_request($this->url,json_encode($codeData));
        $result = json_decode($tmp,true);
	    if (is_array($result) && array_key_exists('errcode', $result)) {
		    return error($result['errmsg'], $result['errcode']);
        }

	    return success(['image' => $this->base64Url($tmp, 'image/png')]);

    }

    protected function base64Url($data,$type){
        return 'data:'.$type.';base64,'.base64_encode($data);
    }


    public function getImageCode($scene='.',$page='pages/index/index'){

        $codeData = [
            'page' => $page,
            'scene' =>$scene
        ];

        $tmp = https_request($this->url,json_encode($codeData));
        $result = json_decode($tmp,true);

	    if (is_array($result) && array_key_exists('errcode', $result)) {
		    return error($result['errmsg'], $result['errcode']);
	    }

        $filename = date('YmdHis').random(6).'.jpg';
        $file = ROOT_PATH.'public/upload/qrcode/'.$filename;
        file_put_contents($file,$tmp);
	    $image = Request::instance()->domain() . '/upload/qrcode/' . $filename;

	    return success(['image' => $image]);


}



}